package com.dudao.modules.course.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.dudao.common.annotation.LogOperation;
import com.dudao.common.constant.Constant;
import com.dudao.common.page.PageData;
import com.dudao.common.utils.ExcelUtils;
import com.dudao.common.utils.Result;
import com.dudao.common.validator.AssertUtils;
import com.dudao.common.validator.ValidatorUtils;
import com.dudao.common.validator.group.AddGroup;
import com.dudao.common.validator.group.DefaultGroup;
import com.dudao.common.validator.group.UpdateGroup;
import com.dudao.modules.course.dto.DudaoArrangeDTO;
import com.dudao.modules.course.entity.CourseInitialEntity;
import com.dudao.modules.course.entity.DudaoArrangeEntity;
import com.dudao.modules.course.excel.DudaoArrangeExcel;
import com.dudao.modules.course.service.DudaoArrangeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.service.ApiInfo;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;


/**
 *
 *
 * @author Lii juliip@163.com
 * @since 1.0.0 2022-12-14
 */
@RestController
@RequestMapping("course/dudaoarrange")
@Api(tags="排督导")
public class DudaoArrangeController {
    @Autowired
    private DudaoArrangeService dudaoArrangeService;

    private static final String PATH = "E:\\桌面\\督导\\实验数据\\test3.py";

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("course:dudaoarrange:page")
    public Result<PageData<DudaoArrangeDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<DudaoArrangeDTO> page = dudaoArrangeService.page(params);

        return new Result<PageData<DudaoArrangeDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("course:dudaoarrange:info")
    public Result<DudaoArrangeDTO> get(@PathVariable("id") Long id){
        DudaoArrangeDTO data = dudaoArrangeService.get(id);

        return new Result<DudaoArrangeDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("course:dudaoarrange:save")
    public Result save(@RequestBody DudaoArrangeDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        dudaoArrangeService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("course:dudaoarrange:update")
    public Result update(@RequestBody DudaoArrangeDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        dudaoArrangeService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("course:dudaoarrange:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        dudaoArrangeService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("course:dudaoarrange:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<DudaoArrangeDTO> list = dudaoArrangeService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, DudaoArrangeExcel.class);
    }

    @PutMapping("arrange-dudao")
    @ApiOperation("排督导")
    @LogOperation("排督导")
    @RequiresPermissions("course:dudaoarrange:arrange")
    public Result arrange() throws Exception {

        final ProcessBuilder processBuilder = new ProcessBuilder("python", PATH);
        processBuilder.redirectErrorStream(true);
        final Process process = processBuilder.start();
        final BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String s = null;
        while ((s = in.readLine()) != null)
        {
            System.out.println(s);
        }

        final int exitCode = process.waitFor();
        System.out.println(exitCode == 0);

        if (exitCode==0) {
            String filePath = "E:\\桌面\\督导\\实验数据\\2.xlsx";
            ImportParams params = new ImportParams();
            params.setHeadRows(1);
            List<DudaoArrangeEntity> dudaoArrangeEntities = readExcel(filePath, DudaoArrangeEntity.class);
            //  List<DudaoArrangeEntity> dudaoArrangeEntities = ExcelImportUtil.importExcel(new File(filePath), DudaoArrangeEntity.class, params);
            String dutyDudao = "";
            for (DudaoArrangeEntity dudaoArrangeEntity : dudaoArrangeEntities) {
                if (dudaoArrangeEntity.getConditions() == null) {
                    dudaoArrangeEntity.setConditions("任选其一");
                }

                if (dudaoArrangeEntity.getDutyDudao()!=null){
                    dutyDudao = dudaoArrangeEntity.getDutyDudao();
                }else {
                    dudaoArrangeEntity.setDutyDudao(dutyDudao);
                }

                String teacherId = dudaoArrangeEntity.getTeacherId();
//              String dutyDudao = dudaoArrangeService.findDudaoById(teacherId);


                dudaoArrangeService.insert(dudaoArrangeEntity);
            }
        }

        return new Result();
    }

    /**
     *
     * @param filePath Excel文件路径
     * @param clazz 对应封装的数据实例对象
     * @return 返回数据集合
     */
    public static <E> List<E> readExcel(String filePath, Class<E> clazz) {
        // 定义输入流
        FileInputStream fis = null;
        List<E> datas = null;

        try {
            // 创建输入流对象
            fis = new FileInputStream(filePath);
            ImportParams params = new ImportParams();
            // 校验Excel文件，去掉空行
            params.setNeedVerify(true);
            // 读取数据
            datas = ExcelImportUtil.importExcel(fis, clazz, params);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return datas;
    }
}
